(function ($) {
    "use strict";
    var FADE_TIME = 150; // ms
    var TYPING_TIMER_LENGTH = 400; // ms
    var COLORS = [
        '#e21400', '#91580f', '#f8a700', '#f78b00',
        '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
        '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
    ];
    var MAX_HIES = 5;
    var $window = $(window);
    var $usernameInput = $('.usernameInput');
    var $messages = $('.messages');
    var $inputMessage = $('.inputMessage');

    var $loginPage = $('.login.page');
    var $indexPage = $('.index.page');

    var username;
    var connected = false;
    var typing = false;
    var lastTypingTime;
    var $currentInput = $usernameInput.focus();
    var menu;
    var dishCount = 0;

    var socket = io();

    function setUsername() {
        username = cleanInput($usernameInput.val().trim());

        // If the username is valid
        if (username) {

            // Tell the server your username
            socket.emit('add user', username);
        }
    }

    function addParticipantsMessage(data) {
        var message = '';
        if (data.numUsers === 1) {
            message += "当前有1个参与者";
        } else {
            message += "当前有" + data.numUsers + "个参与者";
        }
        log(message);
    }

    function removeParticipant(data) {
        $('#participant-' + data.username).remove();
    }

    function addParticipant(data) {
        $('.participants').append(
            $('<div class="participant"/>').html(
                    '<div class="name">' + data.username + '</div><div class="selectedDishes"><p class="empty">还没有点菜</p></div>'
            ).attr('id', 'participant-' + data.username)
        );
    }

    function addParticipants(participants) {
        var $participants = $('.participants');
        $.each(participants, function (uname, selectedDishes) {
            var $participant = $('<div class="participant"/>').html(
                    '<div class="name">' + ( uname === username ? '我' : uname ) + '</div><div class="selectedDishes"></div>'
            ).attr('id', 'participant-' + uname);
            if (uname === username) {
                $participant.addClass('isSelf');
            }
            if (!$.isEmptyObject(selectedDishes)) {
                var items = [];
                $.each(selectedDishes, function (dishName, num) {
                    console.log(dishName, num);
                    var i = 0, price = menu[dishName];
                    for (; i < num; i++) {
                        items.push('<li><span class="name">' + dishName + '</span><span class="price">' + price + '元</span></li>')
                    }
                });
                $participant.find('.selectedDishes').html('<ul class="menu">' + items.join('\n') + '</ul>');
            } else {
                $participant.find('.selectedDishes').html('<p class="empty">还没有点菜</p>')
            }

            $participants.append($participant);
        })
    }

    function buildMenu(menu) {
        var $menu = $('.menuArea').find('.menu'), items = [];
        $.each(menu, function (key, value) {
            items.push('<li><span class="name">' + key + '</span><span class="price">' + value + '元</span></li>')
        });
        $menu.html(items.join('\n'));
    }

    function addDish(data) {
        if (!connected) {
            return;
        }
        var $selectedDishes = $('#participant-' + data.username).find('.selectedDishes');
        var dishName = data.dishName;
        var price = menu[dishName];
        var repeat = false, $item = $('<li><span class="name">' + dishName + '</span><span class="price">' + price + '元</span></li>');
        var $items = $selectedDishes.find('.menu li');
        if ($selectedDishes.find('.menu').length) {
            for (var i = 0, l = $items.length; i < l; i++) {
                if ($items.eq(i).find('.name').html() == dishName) {
                    $items.eq(i).after($item);
                    repeat = true;
                    break;
                }
            }
            if (!repeat) {
                $selectedDishes.find('.menu').append($item);
            }
        } else {
            $selectedDishes.html('<ul class="menu"><li><span class="name">' + dishName + '</span><span class="price">' + price + '元</span></li></ul>');
        }
    }

    function removeDish(data) {
        if (!connected) {
            return;
        }
        var $selectedDishes = $('#participant-' + data.username).find('.selectedDishes');
        if ($selectedDishes.find('.menu').length) {
            $selectedDishes.find('.menu').find('li').eq(data.index).remove();
            if (!$selectedDishes.find('.menu').find('li').length) {
                $selectedDishes.html('<p class="empty">还没有点菜</p>');
            }
        }
    }

    // Sends a chat message
    function sendMessage() {
        var message = $inputMessage.val();
        // Prevent markup from being injected into the message
        message = cleanInput(message);
        // if there is a non-empty message and a socket connection
        if (message && connected) {
            $inputMessage.val('');
            addChatMessage({
                username: username,
                message: message
            });
            // tell server to execute 'new message' and send along one parameter
            socket.emit('new message', message);
        }
    }

    // Log a message
    function log(message, options) {
        var $el = $('<li>').addClass('log').text(message);
        addMessageElement($el, options);
    }

    function logOrder(message, options) {
        if (!connected) {
            return;
        }
        var $el = $('<li>').addClass('order').text(message);
        addMessageElement($el, options);
    }

    // Adds the visual chat message to the message list
    function addChatMessage(data, options) {
        // Don't fade the message in if there is an 'X was typing'
        var $typingMessages = getTypingMessages(data);
        options = options || {};
        if ($typingMessages.length !== 0) {
            options.fade = false;
            $typingMessages.remove();
        }

        var $usernameDiv = $('<span class="username"/>')
            .text(data.username)
            .css('color', getUsernameColor(data.username));
        var $messageBodyDiv = $('<span class="messageBody">')
            .text(data.message);

        var typingClass = data.typing ? 'typing' : '';
        var $messageDiv = $('<li class="message"/>')
            .data('username', data.username)
            .addClass(typingClass)
            .append($usernameDiv, $messageBodyDiv);

        addMessageElement($messageDiv, options);
    }

    // Adds the visual chat typing message
    function addChatTyping(data) {
        data.typing = true;
        data.message = '正在输入';
        addChatMessage(data);
    }

    // Removes the visual chat typing message
    function removeChatTyping(data) {
        getTypingMessages(data).fadeOut(function () {
            $(this).remove();
        });
    }

    // Adds a message element to the messages and scrolls to the bottom
    // el - The element to add as a message
    // options.fade - If the element should fade-in (default = true)
    // options.prepend - If the element should prepend
    //   all other messages (default = false)
    function addMessageElement(el, options) {
        var $el = $(el);

        // Setup default options
        if (!options) {
            options = {};
        }
        if (typeof options.fade === 'undefined') {
            options.fade = true;
        }
        if (typeof options.prepend === 'undefined') {
            options.prepend = false;
        }

        // Apply options
        if (options.fade) {
            $el.hide().fadeIn(FADE_TIME);
        }
        if (options.prepend) {
            $messages.prepend($el);
        } else {
            $messages.append($el);
        }
        $messages[0].scrollTop = $messages[0].scrollHeight;
    }

    // Prevents input from having injected markup
    function cleanInput(input) {
        return $('<div/>').text(input).text();
    }

    // Updates the typing event
    function updateTyping() {
        if (connected) {
            if (!typing) {
                typing = true;
                socket.emit('typing');
            }
            lastTypingTime = (new Date()).getTime();

            setTimeout(function () {
                var typingTimer = (new Date()).getTime();
                var timeDiff = typingTimer - lastTypingTime;
                if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
                    socket.emit('stop typing');
                    typing = false;
                }
            }, TYPING_TIMER_LENGTH);
        }
    }

    // Gets the 'X is typing' messages of a user
    function getTypingMessages(data) {
        return $('.typing.message').filter(function (i) {
            return $(this).data('username') === data.username;
        });
    }

    // Gets the color of a username through our hash function
    function getUsernameColor(username) {
        // Compute hash code
        var hash = 7;
        for (var i = 0; i < username.length; i++) {
            hash = username.charCodeAt(i) + (hash << 5) - hash;
        }
        // Calculate color
        var index = Math.abs(hash % COLORS.length);
        return COLORS[index];
    }

    $window.keydown(function (event) {
        if (!(event.ctrlKey || event.metaKey || event.altKey)) {
            $currentInput.focus();
        }

        // 回车
        if (event.which === 13) {
            if (username) {
                sendMessage();
                socket.emit('stop typing');
                typing = false;
            } else {
                setUsername();
            }
        }
    });

    $inputMessage.on('input', function () {
        updateTyping();
    });

    $loginPage.click(function () {
        $currentInput.focus();
    });

    $inputMessage.click(function () {
        $inputMessage.focus();
    });

    $('.menuArea').on('click', '.menu li', function () {
        if (dishCount >= 5) {
            alert('对不起，一人只能最多点5个菜');
            return;
        }
        dishCount++;
        var dishName = $(this).find('.name').html();
        logOrder('我点了一个' + dishName);
        addDish({username: username, dishName: dishName});
        socket.emit('order dish', dishName);
    });

    $('.participants').on('click', '.menu li', function () {
        var dishName = $(this).find('.name').html(),
            index = $(this).parent().find('li').index(this);
        console.log(index);
        var $participant = $(this).parents('.participant');
        if ($participant.attr('id') !== 'participant-' + username) {
            return;
        }
        dishCount--;
        logOrder('我不要了' + dishName);
        removeDish({username: username, index: index});
        socket.emit('cancel dish', dishName, index);
    });

    // Socket events

    // Whenever the server emits 'login', log the login message
    socket.on('login', function (data) {
        $loginPage.fadeOut();
        $indexPage.show();
        $loginPage.off('click');
        $currentInput = $inputMessage.focus();

        connected = true;
        menu = data.menu;
        // Display the welcome message
        var message = "欢迎来到点菜吧 – ";
        log(message, {
            prepend: true
        });
        buildMenu(data.menu);
        addParticipants(data.participants);
        addParticipantsMessage(data);
    });

    socket.on('login fail', function (data) {
        username = undefined;
        alert(data.message);
    });

    // Whenever the server emits 'new message', update the chat body
    socket.on('new message', function (data) {
        addChatMessage(data);
    });

    // Whenever the server emits 'user joined', log it in the chat body
    socket.on('user joined', function (data) {
        log(data.username + '加入了');
        addParticipantsMessage(data);
        addParticipant(data);
    });

    socket.on('order dish', function (data) {
        logOrder(data.username + '点了一个' + data.dishName);
        addDish(data);
    });

    socket.on('cancel dish', function (data) {
        console.log(data);
        logOrder(data.username + '不要了' + data.dishName);
        removeDish(data);
    });

    // Whenever the server emits 'user left', log it in the chat body
    socket.on('user left', function (data) {
        log(data.username + '离开了');
        addParticipantsMessage(data);
        removeChatTyping(data);
        removeParticipant(data);
    });

    // Whenever the server emits 'typing', show the typing message
    socket.on('typing', function (data) {
        addChatTyping(data);
    });

    // Whenever the server emits 'stop typing', kill the typing message
    socket.on('stop typing', function (data) {
        removeChatTyping(data);
    });
})(jQuery);
